﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Metadata;
using System.Web.Http.Validation;
using System.Web.Http.Validation.Validators;
using System.Net.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http;
using NCS.IConnect.Core.Utilities;
using System.Security.Permissions;
using System.Collections;
using System.Runtime.InteropServices;

namespace NCS.IConnect.Core.WebApi.Validation
{
    /// <summary>
    /// This custom <see cref="ActionFilterAttribute"/> is used for conditional validation.
    /// </summary>
    [ComVisible(false)]
    public class ConditionalValidateAttribute : ActionFilterAttribute
    {
        /// <summary>
        ///  Occurs before the action method is invoked.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        [EnvironmentPermission(SecurityAction.LinkDemand, Unrestricted = true)]
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            foreach (var argument in actionContext.ActionArguments.Values)
            {
                if (argument != null)
                {
                    ModelMetadata metadata = actionContext.GetMetadataProvider().GetMetadataForType(() => argument, argument.GetType());
                    this.ValidateCore(actionContext, metadata, null as object, string.Empty);
                }
            }

            if (!actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, CreateInvalidModelStateError(actionContext.ModelState));
            }
        }

        private HttpErrorInfo CreateInvalidModelStateError(ModelStateDictionary modelState, bool includeErrorDetail = false)
        {
            return new HttpErrorInfo(Errors.E0005.ErrorCode, Errors.E0005.Message, modelState, includeErrorDetail)
            {
                Remark = Errors.E0005.Remark
            };
        }

        private bool ValidateCore(HttpActionContext actionContext, ModelMetadata metadata, object container, string prefix)
        {
            bool isValid = true;
            isValid = this.ValidateElements(actionContext, metadata, container, prefix, isValid);
            if (!isValid)
            {
                return false;
            }

            isValid = this.ValidateProperties(actionContext, metadata, container, prefix, isValid);
            if (!isValid)
            {
                return false;
            }

            if (null != metadata.ContainerType && !string.IsNullOrEmpty(metadata.PropertyName))
            {
                PropertyInfo property = metadata.ContainerType.GetProperty(metadata.PropertyName);
                if (null != property)
                {
                    ConditionalValidationAttribute attribute = AttributeAccessor.GetAttributes<ConditionalValidationAttribute>(property, false).FirstOrDefault();
                    if (null != attribute && attribute.WillValidate(actionContext))
                    {
                        DataAnnotationsModelValidator validator = new DataAnnotationsModelValidator(new ModelValidatorProvider[0], attribute.CreateValidationAttribute());
                        foreach (var result in validator.Validate(metadata, container))
                        {
                            actionContext.ModelState.AddModelError(prefix, result.Message);
                            isValid = false;
                        }
                    }
                }
            }

            return isValid;
        }

        private bool ValidateProperties(HttpActionContext actionContext, ModelMetadata metadata, object container, string prefix, bool isValid)
        {
            if (!IsSimpleType(metadata) && !(metadata.Model is IEnumerable))
            {
                foreach (ModelMetadata property in metadata.Properties)
                {
                    string key = this.GetModelStateKey(prefix, property.PropertyName);
                    if (!this.ValidateCore(actionContext, property, metadata.Model, key))
                    {
                        isValid = false;
                    }
                }
            }
            return isValid;
        }

        private bool ValidateElements(HttpActionContext actionContext, ModelMetadata metadata, object container, string prefix, bool isValid)
        {
            IEnumerable collection = metadata.Model as IEnumerable;
            if (null != collection && !(collection is string))
            {
                int index = 0;
                Type elementType = this.GetElementType(metadata.ModelType);
                foreach (var item in collection)
                {
                    ModelMetadata elementMetadata = actionContext.GetMetadataProvider().GetMetadataForType(() => item, elementType);
                    string key = this.GetModelStateKey(prefix, index++);
                    if (!this.ValidateCore(actionContext, elementMetadata, elementMetadata.Model, key))
                    {
                        isValid = false;
                    }
                }
            }
            return isValid;
        }

        private Type GetElementType(Type type)
        {
            if (type.IsArray)
            {
                return type.GetElementType();
            }

            foreach (Type interfaceType in type.GetInterfaces())
            {
                if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                {
                    return interfaceType.GetGenericArguments()[0];
                }
            }

            return typeof(object);
        }

        private string GetModelStateKey(string prefix, object name)
        {
            if (name is int)
            {
                return string.Format("{0}[{1}]", prefix, (int)name);
            }
            return string.Format("{0}.{1}", prefix ?? "", name ?? "").Trim('.');
        }

        private bool IsSimpleType(ModelMetadata property)
        {
            Type type = property.ModelType;
            Type elementType = this.GetElementType(property.ModelType);
            if (typeof(object) != elementType)
            {
                type = elementType;
            }
            return type.IsPrimitive || type.Equals(typeof(string)) || type.Equals(typeof(DateTime)) || type.Equals(typeof(decimal)) || type.Equals(typeof(Guid)) || type.Equals(typeof(DateTimeOffset)) || type.Equals(typeof(TimeSpan));
        }
    }
}